package org.example.api.source;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.example.api.bean.SensorReading;

import java.util.HashMap;
import java.util.Random;

/**
 * @author huangqihan
 * @date 2021/2/18
 */
public class SourceFromUDF {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<SensorReading> sensorReadingDataStreamSource = env.addSource(new SensorSource());
        sensorReadingDataStreamSource.print();

        env.execute();
    }

    static class SensorSource implements SourceFunction<SensorReading> {

        private boolean running = true;

        @Override
        public void run(SourceContext<SensorReading> sourceContext) throws Exception {
            // 随机数发生器
            Random random = new Random();

            // 设置10个传感器初始温度
            HashMap<String, Double> hashMap = new HashMap<>(10);
            for (int i = 0; i < 10; i++) {
                hashMap.put("sensor_" + (i + 1), 60 + random.nextGaussian() * 20);
            }

            while (running) {

                // 在基础数值下随机上下波动
                for (String id : hashMap.keySet()) {
                    double temp = hashMap.get(id) + random.nextGaussian();
                    hashMap.put(id, temp);
                    sourceContext.collect(new SensorReading(id, System.currentTimeMillis(), temp));
                }
                // 控制数据输出频率
                Thread.sleep(2000L);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }

}
